//
//  RoomViewController.swift
//  七哥直播
//
//  Created by seven on 2017/12/20.
//  Copyright © 2017年 seven. All rights reserved.
//

import UIKit
import Kingfisher

private let kChatToolsViewHeight : CGFloat = 44
private let kGiftListViewHeight: CGFloat = kScreenH * 0.4
private let kChatContentViewHeight : CGFloat = 200

class RoomViewController: UIViewController,Emitterable {
    
    // MARK: 控件属性
    @IBOutlet weak var bgImageView: UIImageView!
    private lazy var chatToolsView: ChatToolsView = ChatToolsView.loadFromNib()
    private lazy var giftView: GiftListView = GiftListView.loadFromNib()
    private lazy var chatContentView: ChatContentView = ChatContentView.loadFromNib()
    private lazy var socket: HYSocket = HYSocket(addr: "192.168.10.104", port: 7878)
    private var headrtBeatTimer: Timer?
    // MARK: 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        if socket.connectServer(){
            print("链接成功")
            addHeartBeatTimer()
            socket.sendJoinRoom()
            socket.startReadMsg()
            socket.delegate = self
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        socket.sendLeaveRoom()
    }
    
    deinit {
        headrtBeatTimer?.invalidate()
        headrtBeatTimer = nil
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        chatToolsView.inputTextField.resignFirstResponder()
        UIView.animate(withDuration: 0.25) {
            self.giftView.frame.origin.y = self.view.bounds.height
        }
    }
    
}


// MARK:- 设置UI界面内容
extension RoomViewController {
    private func setupUI(){
        setupBlurView()
        setupBottomView()
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    private func setupBlurView(){
        let blur = UIBlurEffect(style: .dark)
        let blurView = UIVisualEffectView(effect: blur)
        blurView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
        blurView.frame = bgImageView.bounds
        bgImageView.addSubview(blurView)
    }
    
    private func setupBottomView() {
        //3.设置chat内容的View
        chatContentView.frame = CGRect(x: 0, y: view.bounds.height - 44 - kBottomSafeArea - kChatContentViewHeight, width: view.bounds.width, height: kChatContentViewHeight)
        chatContentView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
        view.addSubview(chatContentView)
        //1.设置chateView
        chatToolsView.frame = CGRect(x: 0, y: view.bounds.height, width: view.bounds.width, height: kChatToolsViewHeight)
        chatToolsView.autoresizingMask = [.flexibleTopMargin,.flexibleWidth]
        chatToolsView.delegate = self
        view.addSubview(chatToolsView)
        
        //2.设置giftView
        giftView.frame = CGRect(x: 0, y: view.bounds.height, width: view.bounds.width, height: kGiftListViewHeight)
        giftView.autoresizingMask = [.flexibleTopMargin,.flexibleWidth]
        giftView.delegate = self
        view.addSubview(giftView)
        
    }
}

//MARK:- 点击事件监听
extension RoomViewController{
    
    @IBAction func exitClick(_ sender: UIButton) {
        navigationController?.popViewController(animated: true)
    }
    
    @IBAction func bottomMenuClick(_ sender: UIButton) {
        switch sender.tag {
        case 0:
            chatToolsView.inputTextField.becomeFirstResponder()
        case 1:
            print("点击了分享")
        case 2:
            print("点击了礼物")
            UIView.animate(withDuration: 0.25, animations: {
                self.giftView.frame.origin.y = self.view.bounds.height - kGiftListViewHeight - kBottomSafeArea
            })
        case 3:
            print("点击了更多")
        case 4:
            sender.isSelected = !sender.isSelected
            let point = CGPoint(x: sender.center.x, y: view.bounds.height - sender.bounds.height - kBottomSafeArea)
            sender.isSelected ? startEmittering(point) : stopEmittering()
        default:
            fatalError("未处理的按钮点击")
        }
    }
    
    //键盘弹出监听
    @objc private func keyboardWillChangeFrame(_ note : Notification) {
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let endFrame = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let inputViewY = endFrame.origin.y - kChatToolsViewHeight
        
        UIView.animate(withDuration: duration, animations: {
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: 7)!)
            let endY = inputViewY == (kScreenH - kChatToolsViewHeight) ? kScreenH : inputViewY
            self.chatToolsView.frame.origin.y = endY
            let chatContentY = inputViewY == (kScreenH - kChatToolsViewHeight) ? kScreenH - kChatContentViewHeight - 44 - kBottomSafeArea: endY - kChatContentViewHeight
            self.chatContentView.frame.origin.y = chatContentY
        })
    }
}

extension RoomViewController: ChatToolsViewDelegate,GiftListViewDelegate{
    func chatToolsView(toolView: ChatToolsView, message: String) {
        socket.sendTextMsg(message: message)
    }
    func giftListView(giftView: GiftListView, giftModel: GiftModel) {
        socket.sendGiftMsg(giftName: giftModel.subject, giftURL: giftModel.img2, giftCount: 1)
    }
}

//MARK:- 给服务器发送即时消息
extension RoomViewController{
    private func addHeartBeatTimer(){
        headrtBeatTimer = Timer(fireAt: Date(), interval: 9, target: self, selector: #selector(sendHeartBeat), userInfo: nil, repeats: true)
        RunLoop.main.add(headrtBeatTimer!, forMode: .commonModes)
    }
    @objc private func sendHeartBeat(){
        socket.sendHeartBeat()
    }
}
//MARK:- socketDelegate
extension RoomViewController: HYSocketDelegate{
    func socket(_ socket: HYSocket, joinRoom user: UserInfo) {
        let message = AttrStriingGenetator.generateJoinLeaveRoom(userName: user.name!, isJoin: true)
        chatContentView.insertMsg(message)
    }
    func socket(_ socket: HYSocket, leaveRoom user: UserInfo) {
        
        let message = AttrStriingGenetator.generateJoinLeaveRoom(userName: user.name!, isJoin: true)
        chatContentView.insertMsg(message)
    }
    func socket(_ socket: HYSocket, chatMsg: ChatMessage) {
        let message = AttrStriingGenetator.generateTextMessage(userName: chatMsg.user.name!, message: chatMsg.text)
        chatContentView.insertMsg(message)
    }
    
    func socket(_ socket: HYSocket, giftMsg: GiftMessage) {
        let message = AttrStriingGenetator.generateGiftMessage(giftname: giftMsg.giftname!, giftURL: giftMsg.giftUrl, userNmae: giftMsg.user.name)
        chatContentView.insertMsg(message)
    }

}

